﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class CheckEnemy : MonoBehaviour {

    public List<GameObject> enemyList = new List<GameObject>();
    public GameObject nearEnemy;

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        CheckNearEnemy();
    }

    private void OnTriggerEnter2D(Collider2D collision)
    {
        if (collision.tag == "Enemy")
        {
            print("添加敌人");
            enemyList.Add(collision.gameObject);
        }
    }

    private void OnTriggerExit2D(Collider2D collision)
    {
        if (collision.tag == "Enemy")
        {
            if (enemyList.Contains(collision.gameObject))
            {
                print("移除敌人");
                enemyList.Remove(collision.gameObject);
            }
        }
    }

    /// <summary>
    /// 检查范围内最近的敌人
    /// </summary>
    private void CheckNearEnemy()
    {
        if (enemyList.Count > 0)
        {
            float distance = 1000;
            for (int i = 0; i < enemyList.Count; i++)
            {
                float tempDistance = Vector3.Distance(transform.position, enemyList[i].transform.position);
                if (tempDistance < distance)
                {
                    distance = tempDistance;
                    nearEnemy = enemyList[i];
                }
            }
        }
    }




}
